package com.study.concurrency;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

import lombok.Data;

/*
线程1实现 10加到100
线程2实现 100加到200
线程3实现 线程1和线程2计算结果的和

 */
public class CountDownLatchDemo {

	public static CountDownLatch countDown = new CountDownLatch(2);

	public static CountDownLatch getCountDown() {
		return countDown;
	}

	public static void setCountDown(CountDownLatch count) {
		CountDownLatchDemo.countDown = count;
	}
	
	public static void main(String[] args) {
		
		MyThread myThread1 = new MyThread(10, 100);
		MyThread myThread2 = new MyThread(100, 200);
		
		
		Thread thread3 = new Thread(new Runnable(){
			
			@Override
			public void run() {
				try {
					CountDownLatchDemo.getCountDown().await();   //等待countDown 为零
					System.out.println("总和为: " + (myThread1.getSum() + myThread2.getSum())); 
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		});
		
		new Thread(myThread1).start();
		new Thread(myThread2).start();
		thread3.start();
		
	}
	
	
}

@Data
class MyThread implements Runnable{
	private int start;
	private int end;
	private int sum;
	public MyThread(int start, int end){
		this.end = end;
		this.start = start;
		this.sum = 0;
	}
	
	@Override
	public void run() {
		try {
			Thread.sleep(new Random().nextInt(2000));
			
			for(int i=start; i <=end; i++){
				sum += i;
			}
			
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			System.out.println(Thread.currentThread().getName() + "结束;结果为：" + this.sum);
			CountDownLatchDemo.getCountDown().countDown(); //countDown减1
		}
		
	}
}